import { createRouter, createWebHistory } from 'vue-router'
import routesConfig from './config'
import { useLoginStore } from '@/stores/index'

const routes = [
  { path: '/login', name: 'login', component: () => import('@/views/LoginView.vue') },
  { path: '/main', name: 'main', component: () => import('@/views/MainView.vue') },
]
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})
// 路由守卫
router.beforeEach((to, from, next) => {
  const loginStore = useLoginStore()
  if (to.name === 'login') {
    next()
  } else {
    //如果已授权 next() 否则 重定向到登录页面
    if (!loginStore.token || loginStore.token === '') {
      next({ path: '/login' })
    } else {
      //如果第一次
      if (loginStore.isFirstInit) {
        configRouter()
        //设置initState
        loginStore.setIsFirstInit(false)
        // 解决刷新页面路由丢失问题
        // loginStore.setRoutes(routesConfig)

        next({
          path: to.fullPath,
        })
      } else {
        next()
      }
    }
  }
})
const configRouter = () => {
  routesConfig.forEach((route) => {
    router.addRoute('main', route)
  })
}
export default router
